#include "main/utils.h"
#include "lib/binary_tree.h"
using namespace std;

using TreeNode = BinaryTreeNode;

class Solution {
public:
    TreeNode* trimBST(TreeNode* root, int low, int high) {
      if (!root)
        return nullptr;
      if (root->value < low) {
        return trimBST(root->right, low, high);
      } else if (root->value > high) {
        return trimBST(root->left, low, high);
      } else {
        root->left = trimBST(root->left, low, high);
        root->right = trimBST(root->right, low, high);
        return root;
      }
      return nullptr;
    }

    TreeNode* trimBST_iteration(TreeNode* root, int low, int high) {
      while (root && (root->value < low || root->value > high)) {
        if (root->value < low)
          root = root->right;
        if (root->value > high)
          root = root->left;
      }
      if (!root)
        return nullptr;

      auto cur = root;
      while (cur->left) {
        if (cur->left->value < low) {
          cur->left = cur->left->right;
        } else {
          cur = cur->left;
        }
      }

      cur = root;
      while (cur->right) {
        if (cur->right->value > high) {
          cur->right = cur->right->left;
        } else {
          cur = cur->right;
        }
      }
      return root;
    }
};

int main() {
  vector<int> vec = {3, 1, 5, 0, 2, 4, 6};

  BinaryTreeNode* root = CreateBinaryTree(vec);
  PrintBinaryTree(root);

  Solution su;
  auto ret = su.trimBST(root, 1, 5);
  PrintBinaryTree(ret);

  BinaryTreeNode* root1 = CreateBinaryTree(vec);
  auto ret1 = su.trimBST_iteration(root1, 1, 5);
  PrintBinaryTree(ret1);

  return 0;
}
